//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: sspg
// 
// Create Date: 2018/07/12 13:41:30
// Design Name: 
// Module Name: irig_width_decode
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description:  
//      Decode the IRIG-B width-encoded bits into data 0, data 1, and mark signals 
//             
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 100ps
module irig_width_decode (
    input           rst,
    input           clk,
    input           irigb,
    
    output reg      irigb_invalid,
    output reg      irig_mark,
    output reg      irig_d0,
    output reg      irig_d1
    );
    
    
// 10MHz clock and 10kHz IRIG-B
// Width encoding of the three states
localparam CYCLES_ZERO_L = 17'd15000;//17'd20000;
localparam CYCLES_ZERO_H = 17'd25000;//17'd20000;
localparam CYCLES_ONE_L  = 17'd45000;//17'd50000;
localparam CYCLES_ONE_H  = 17'd55000;//17'd50000;
localparam CYCLES_MARK_L = 17'd75000;//17'd80000;
localparam CYCLES_MARK_H = 17'd85000;//17'd80000;
// Clock cycles in an IRIG bit
reg [16:0]                       clk_cnt = 17'b0;
reg                              irigb_last = 1'b0;

always @(posedge clk) begin
    if (rst) begin
        clk_cnt <= 17'b0;
        irigb_last = 1'b0;
        irig_d0 <= 1'b0;
        irig_d1 <= 1'b0;
        irig_mark <= 1'b0;
        irigb_invalid <= 1'b1;
    end else begin
        irigb_last <= irigb;
        // Check widths at irig falling edge and produce one-cycle pulse
        irig_mark <= (clk_cnt > CYCLES_MARK_L) && (clk_cnt < CYCLES_MARK_H) && !irigb && irigb_last && !irig_mark;
        irig_d1   <= (clk_cnt > CYCLES_ONE_L) && (clk_cnt < CYCLES_ONE_H) && !irigb && irigb_last && !irig_d1;
        irig_d0   <= (clk_cnt > CYCLES_ZERO_L) && (clk_cnt < CYCLES_ZERO_H) && !irigb && irigb_last && !irig_d0;
        
        // Reset count on rising edge of irig bit
        if (irigb && !irigb_last)
            clk_cnt <= 17'b0;
        else
            clk_cnt <= clk_cnt + 17'b1;
        
        if (&clk_cnt)
            irigb_invalid <= 1'b1;
        else if(irig_mark | irig_d1 | irig_d0)
            irigb_invalid <= 1'b0;


    end
end
    
endmodule
